#import "MRSideViewController.h"

@implementation MRSideViewController

- (id)init
{
    if (self = [super init])
    {
        _imgBackground = [UIImageView new];
        [self.view addSubview:_imgBackground];
    }
    return self;
}

/*===================================================================
 说明:
    初始化
 ==================================================================*/
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _showFrame = CGRectInset(self.view.bounds, -36, -64);
    _animationDuration = 0.3;
    
    _panGestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(gestureRecognizerEvent:)];
    _panGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:_panGestureRecognizer];
    
    _coverButton = [[UIButton alloc] initWithFrame:self.view.bounds];
    [_coverButton addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    
    _coverImage = [[UIImageView alloc] initWithFrame:self.view.bounds];
    _coverImage.userInteractionEnabled = YES;
    [_coverImage addSubview:_coverButton];
}

/*===================================================================
 说明:
    设置展示菜单后主视图框架（框架宽度自动计算）
 ==================================================================*/
- (void)setShowFrame:(CGRect)showFrame
{
    CGSize size = self.view.frame.size;
    
    _showFrame = showFrame;
    _showFrame.size.width = showFrame.size.height * size.width / size.height;
    
    _translatePoint.x = _showFrame.origin.x - (size.width - _showFrame.size.width) / 2.0f;
    _translatePoint.y = _showFrame.origin.y - (size.height - _showFrame.size.height) / 2.0f;
}

/*===================================================================
 说明:
    设置背影图片
 ==================================================================*/
- (void)setBackgroundImage:(UIImage *)backgroundImage
{
    [_imgBackground setImage:backgroundImage];
    //[_imgBackground tileToSuperview];
}
- (UIImage *)backgroundImage
{
    return _imgBackground.image;
}

/*===================================================================
 说明:
    设置边栏控制器
 ==================================================================*/
- (void)setSideViewController:(UIViewController *)sideViewController
{
    if (_sideViewController != sideViewController)
    {
        if (_sideViewController) [_sideViewController removeFromParentViewController];

        _sideViewController = sideViewController;
        if (_sideViewController) [self addChildViewController:_sideViewController];
        
        _sideView = sideViewController.view;
        _sideView.backgroundColor = [UIColor clearColor];
        _sideView.alpha     = 0.3;       
        _sideView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
    }
}

/*===================================================================
 说明:
    设置根控制器
 ==================================================================*/
- (void)setMainViewController:(UIViewController *)mainViewController
{
    if (mainViewController && _mainViewController != mainViewController)
    {
        _lastViewController = _mainViewController;
        _lastView = _mainView;
        
        _mainViewController = mainViewController;
        _mainView = _mainViewController.view;
        
        [self addChildViewController:_mainViewController];
        [self.view addSubview:_mainView];
        
        if (_lastView.frame.origin.x)       //已显示菜单
        {
            _mainView.transform = _lastView.transform;
        }
        
        if (_lastViewController) _mainView.alpha = 0;
        [self toggle];
    }
}

#pragma mark - ShowOrHideTheView
/*===================================================================
 说明:
    显示根控制器的阴影
 ==================================================================*/
- (void)showShadow:(BOOL)show
{
    
}

/*===================================================================
 说明:
    切换菜单
 ==================================================================*/
- (void)toggle
{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [UIView animateWithDuration:_animationDuration animations:^{
        [self layoutViewWithOffset:0];
        
    } completion:^(BOOL finished){
        [self showShadow:false];
        [_sideView removeFromSuperview];
        [_lastView removeFromSuperview];
        [_lastViewController removeFromParentViewController];
         
        _lastView = nil;
        _lastViewController = nil;
    }];
}

/*===================================================================
 说明:
    展示边栏
 ==================================================================*/
- (void)show
{
    [self.view insertSubview:_sideView belowSubview:_mainView];
    [self showShadow:true];
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [UIView animateWithDuration:_animationDuration animations:^{
        [self layoutViewWithOffset:1];
    }];
}

/*===================================================================
 说明:
    隐藏边栏
 ==================================================================*/
- (void)hide
{
    if (_mainView.frame.origin.x) [self toggle];
}

#pragma mark - 手势处理
/*===================================================================
 说明:
    检测是否可以滑动到菜单
 ==================================================================*/
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer == _panGestureRecognizer)
    {
        NSUInteger i = 1;
        CGPoint pt = [gestureRecognizer locationInView:self.view];
        
        if ([_mainViewController isKindOfClass:[UINavigationController class]])
        {
            i = ((UINavigationController *)_mainViewController).viewControllers.count;
        }
        
        /*if (i > 1) return NO;
        if (_mainView.frame.origin.x == 0 && pt.x > 30) return NO;
        if (!CGRectContainsPoint(_mainView.frame, pt)) return NO;*/
        
        return (i == 1 && (_mainView.frame.origin.x || pt.x <= 30));
    }
    return YES;
}

/*===================================================================
 说明:
    手势处理
 ==================================================================*/
- (void)gestureRecognizerEvent:(UIPanGestureRecognizer *)panGestureRecognizer
{
    //开始手势
    if (panGestureRecognizer.state == UIGestureRecognizerStateBegan)
    {
        _startPanPoint = _mainView.frame.origin;
        
        if (_sideViewController && _sideView.superview == nil)
        {
            [self showShadow:true];
            [self.view insertSubview:_sideView belowSubview:_mainView];
        }
        return;
    }
    
    CGPoint currentPostion = [panGestureRecognizer translationInView:self.view];
    CGFloat x = _startPanPoint.x + currentPostion.x;
    
    //只允许向右滑出左边栏
    if (x > 0 && _sideViewController && _sideView.superview)
    {
        [self layoutViewWithOffset:x / _showFrame.origin.x];
    }
    
    //手势结束时按需完成动画
    if (panGestureRecognizer.state == UIGestureRecognizerStateEnded)
    {
        if (_startPanPoint.x)
        {
            if (currentPostion.x <= -50) [self hide]; else [self show];
        }
        else
        {
            if (currentPostion.x >= 50) [self show]; else [self hide];
        }
    }
}

/*===================================================================
 说明:
    动画效果
    offset 为动画偏移完成百分比，为1时全部完成
 ==================================================================*/
- (void)layoutViewWithOffset:(CGFloat)offset
{
    //主视图缩放&平移
    CGSize  size  = self.view.frame.size;
    CGFloat scale = 1.0f - (size.height - _showFrame.size.height) * offset / size.height;
    
    if (scale < 0.3f) scale = 0.3f;
    CGAffineTransform t = CGAffineTransformMakeScale(scale, scale);
    _mainView.transform = CGAffineTransformTranslate(t, _translatePoint.x * offset / scale, _translatePoint.y * offset / scale);
    
    _mainView.alpha = 1;
    _mainView.layer.shadowPath = [UIBezierPath bezierPathWithRect:_mainView.bounds].CGPath;
    
    //模糊视图
    _coverImage.alpha = offset;
    
    //切换控制器
    if (_lastView) _lastView.transform = _mainView.transform;
    
    //边栏视图缩放效果
    scale = 1.5f - offset * 0.5f;
    if (scale < 0.6f) scale = 0.6f;
    
    _sideView.transform = CGAffineTransformMakeScale(scale, scale);
    _sideView.alpha     = offset * 0.7f + 0.3f;
    _sideView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:(scale < 1.0f ? (1.0f - scale) / 2 : 0.0f)];
}

@end
